import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import store from '../store'
import router from '../router'
const instance = axios.create({
  headers: {
    'Content-Type': 'application/json'
    // 'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: [function (data, config) {
    if (config['Content-Type'] === 'application/x-www-form-urlencoded') data = qs.stringify(data)
    if (config['Content-Type'] === 'application/json') {
      data = JSON.stringify(data)
    }
    return data
  }],
  withCredentials: true,
  timeout: 180000
})
// 配置请求
instance.interceptors.request.use(config => {
  if (config.method === 'get' || config.method === 'delete') {
    config.params = config.data
  }
  // 判断是否登录
  const adminID = store.state.adminId
  const token = store.state.token
  if (adminID) {
    // 登录
    config.headers.auth = 'Bearer '+token
  } else {
    router.push('/login')
  }
  return config
})
// 配置返回值
instance.interceptors.response.use(response => {
  if (response.config.type) {
    return response.data
  }
  const res = response.data
  const success = Number(res.code) === 1000
  if (response.status === 200 && success) {
    if (res.page_info) return res
    return res.data || res
  }
  const e = { message: res.message || '请求失败！', status: '1' }
  Message({
    message: e.message || 'Error',
    type: 'error',
    duration: 3 * 1000
  })
  return Promise.reject(e)
}, error => {
  const status = error && error.response && error.response.status ? error.response.status : 0
  const e = { message: '请求失败！', status: '1' }
  if (status === 404) {
    e.status = '2'
  }
  return Promise.reject(e)
})

export default instance
